package com.wenx.v3system.modular.oauth.controller;

import com.wenx.v3system.modular.oauth.dto.OAuth2TokenResponseDto;
import com.wenx.v3system.modular.oauth.service.OAuth2TokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

import static com.wenx.v3core.util.HttpServletUtil.getClientIp;

/**
 * OAuth2令牌管理控制器
 * 
 * @author wenx
 */
@Slf4j
@Controller
@RequiredArgsConstructor
public class Oauth2TokenController {

    private final OAuth2TokenService oauth2TokenService;

    /**
     * OAuth2授权回调处理
     * 处理授权码，交换令牌，成功后重定向到dashboard页面
     */
    @GetMapping("/oauth2/callback")
    public String handleCallback(
            @RequestParam(value = "code", required = false) String code,
            @RequestParam(value = "state", required = false) String state,
            @RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "error_description", required = false) String errorDescription,
            HttpServletRequest request) {
        
        String clientIp = getClientIp(request);
        log.info("OAuth2授权回调 - IP: {}, code: {}, state: {}, error: {}", 
                clientIp, 
                code != null ? "存在" : "无", 
                state != null ? "存在" : "无", 
                error);
        
        // 处理授权错误
        if (error != null) {
            log.error("OAuth2授权失败: {} - {}", error, errorDescription);
            return "redirect:/dashboard?error=" + error + "&error_description=" + (errorDescription != null ? errorDescription : "");
        }
        
        // 处理授权码，交换令牌
        if (code != null) {
            try {
                OAuth2TokenResponseDto result = oauth2TokenService.exchangeToken(code, clientIp);
                
                if (result != null) {
                    log.info("OAuth2令牌交换成功 - IP: {}, tokenType: {}", clientIp, result.getTokenType());
                    // 成功后重定向到dashboard页面，可以通过URL参数传递成功信息
                    return "redirect:/dashboard?token_success=true";
                } else {
                    log.warn("OAuth2令牌交换失败 - IP: {}", clientIp);
                    return "redirect:/dashboard?error=token_exchange_failed";
                }
                
            } catch (Exception e) {
                log.error("OAuth2令牌交换异常 - IP: {}, error: {}", clientIp, e.getMessage(), e);
                return "redirect:/dashboard?error=token_exchange_error&error_description=" + e.getMessage();
            }
        }
        
        // 缺少必要参数
        log.warn("OAuth2回调缺少必要参数 - IP: {}", clientIp);
        return "redirect:/dashboard?error=invalid_request&error_description=缺少必要的回调参数";
    }


} 